<template>
  <div class="centerWarp" v-loading="allCheckLoading">
    <div>
      <el-card class="box-card">
        <div class="nameStyle" :style="{ height: heightCard }">
          <table
            class="myTable"
          >
            <tr>
              <th style="color: black;width: 100px;">姓名</th>
              <th style="color: black;text-align: left;">工作单位及职务</th>
            </tr>
            <tr
              v-for="(item, index) in personList"
              :key="index"
              @click="handlePersonListClick(item, index)"
            >
              <td
                style="text-align:center"
                :class="{
                  highlight:
                    item.dataId === (curPersonRow && curPersonRow.dataId),
                }"
              >
                {{ item.personName }}
              </td>
              <td
                 style="text-align:left"
                :class="{
                  highlight:
                    item.dataId === (curPersonRow && curPersonRow.dataId),
                }"
              >{{item.jobShort}}</td>
            </tr>
          </table>
        </div>
      </el-card>
    </div>
    <!-- <div>
      <el-card class="box-card">
        <div :style="{ height: heightCard }" class="selectimgs-warp">
          <h2>授权表：</h2>
          <p>{{ getEmpowerTextNotJpg }}</p>
        </div>
      </el-card>
    </div> -->
    <div class="left" :style="{ height: heightTree }">
      <el-tree
        ref="tree"
        class="dc-tree-c"
        :data="personTreeList"
        node-key="id"
        :props="defaultProps"
        highlight-current
        @node-click="handleTreeNodeClick"
        :current-node-key="currentNodekey"
        :default-expanded-keys="[currentNodekey]"
      ></el-tree>
    </div>
    <div class="right">
      <div class="thumbnail" :style="{ height: heightY }">
        <div style="display: flex">
          <el-checkbox
            :indeterminate="isAllIndeterminate"
            v-model="isAllCheckbox"
            @change="handleCheckAllChange"
            >全选全部</el-checkbox
          >
          <el-checkbox
            :indeterminate="isAllNowadayIndeterminate"
            v-model="isAllNowadayCheckbox"
            @change="handleCheckAllNowadayChange"
            >全选当前目录</el-checkbox
          >
        </div>
        <!-- 图片和选择框 -->
        <el-checkbox-group :value="curSelectImageList">
          <div
            class="image-container"
            v-for="(item, index) in imagesSelectList"
            :key="index"
          >
            <el-checkbox
              :key="item.elecId"
              :label="getDictName + '_' + item.fileName"
              @change="
                handleCheckboxChange($event, getDictName + '_' + item.fileName)
              "
            ></el-checkbox>
            <img
              class="cd-checkiam"
              :class="{ 'check-active': index === selectedImageIndex }"
              :src="item.tImg"
              @click="hanldeSelectImage(index)"
            />
          </div>
        </el-checkbox-group>
      </div>
      <div class="bigPicture" :style="{ height: heightY }">
        <img
          :src="
            selectedImageIndex !== null && imagesSelectList[selectedImageIndex]
              ? imagesSelectList[selectedImageIndex].tImg
              : ''
          "
          alt=""
          style="width: 100%; height: 100%"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  getMaterialTree,
  clickMaterial,
  getImgFromCacheByFlag,
} from "@/api/datacentersg/achives/documentApi";

import { treeToList } from "@/utils/index.js";

export default {
  name: "DocumentCenter",
  props: {
    personList: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    personList: {
      deep: true,
      handler(val) {
        // const [item] = val;
        // this.imagesCheckVals = []
        // this.tempImagesCheckVals = []
        // this.handlePersonList(item, 0);
      },
    },
    curSelectImageList(val) {
      if (val.length === 0) {
        this.isAllNowadayCheckbox = false;
        this.isAllNowadayIndeterminate = false;
      } else if (val.length === this.imagesSelectList.length) {
        this.isAllNowadayCheckbox = true;
        this.isAllNowadayIndeterminate = false;
      } else {
        this.isAllNowadayCheckbox = false;
        this.isAllNowadayIndeterminate = true;
      }
    },
  },
  computed: {
    getDictName() {
      const { name } = this.currentTreeItem || {};
      console.log(name, "tree树的名称");
      return name || "";
    },
    getEmpowerText() {
      // 给后端保存的时候可以 使用这个
      if (this.isAllCheckbox) return "全部";
      let selectImages = this.imagesCheckVals;
      return selectImages.join(",");
    },
    getEmpowerTextNotJpg() {
      if (this.isAllCheckbox) return "全部"; // 这个就是 展示 全部 文字，不需要了直接注解就行
      let selectImages = this.imagesCheckVals;
      let txt = selectImages.join(",");
      return txt.replace(new RegExp(".jpg", "g"), "");
    },
  },
  data() {
    return {
      heightCard: window.innerHeight - 320 + "px",
      heightY: window.innerHeight - 280 + "px",
      heightTree: window.innerHeight - 280 + "px",
      defaultProps: {
        children: "children",
        label: "name",
      },
      personTreeList: [],
      currentNodekey: "",
      currentTreeItem: null,
      curPersonRow: null, // 选择人员的
      isAllIndeterminate: false, // 半选状态 这两个可以忽略
      isAllCheckbox: false, // 是不是全选 这两个可以忽略
      imagesSelectList: [], // 当前的图片列表，是根据每个 子集获取的
      imagesCheckVals: [], // 选中的图片
      selectedImageIndex: 0, // 当前图片
      tempImagesCheckVals: [], // 暂存 选中的数据
      personParentImageTreeList: [], // 所有的子集集合
      allCheckLoading: false,
      tcurrentSelectImage: [],
      name: "",
      idCard: "",
      isAllNowadayIndeterminate: false,
      isAllNowadayCheckbox: false,
      curSelectImageList: [], // 当前的点击目录的图片
    };
  },
  mounted() {
    this.imagesCheckVals = [];
    this.tempImagesCheckVals = [];
  },
  methods: {
    handlePersonList(item, ix) {
      console.log(item, "item");
      if (item) {
        this.curPersonRow = item;
        this.name = item.personName;
        this.idCard = item.idCard;
        this.setSelectPersonItemData(item);
        this.getMaterialTree();
      }
    },
    handlePersonListClick(item, index) {
      this.isAllCheckbox = false;
      this.imagesCheckVals = [];
      this.tempImagesCheckVals = [];
      this.curSelectImageList = [];

      // 处理操作人员的信息
      this.handlePersonList(item, index);
    },
    // tree树的数据
    getMaterialTree() {
      const params = {
        name:this.name,
        idCard:this.idCard,
        // name: "谢逊",
        // idCard: "530121198502181698",
      };
      getMaterialTree(params).then((res) => {
        const { res_code, res_data, res_msg } = res.data;
        if (res_code === "0000") {
          this.personTreeList = res_data;
          this.personParentImageTreeList = this.getNotChildrens(
            treeToList(res_data)
          );
          this.handleTreeNodeClick(this.getMateItem(this.personTreeList));
        } else if (res_code === "0001") {
          this.personTreeList = [];
          this.imagesSelectList = [];
          this.$message({
            message: res_msg,
            type: "warning",
          });
        }
      });
    },
    handleTreeNodeClick(e) {
      if (Array.isArray(e.children)) return;
      this.currentTreeItem = e;
      this.currentNodekey = e.id;
      // console.log('treeid', e.id)
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(e.id);
      });
      this.getSelectImages(this.currentNodekey).then((res) => {
        this.imagesSelectList = res;
        this.setTreeSelectImages(); // 初始化当前目录的选择
        this.getImagesSelectList();
      });
    },

    getSelectImages(maid) {
      // console.log(maid,"maid")
      return new Promise((resolve, reject) => {
        const params = {
          name:this.name,
          idCard:this.idCard,
          // name: "谢逊",
          // idCard: "530121198502181698",
          materialid: maid, //点击的目录ID
        };
        clickMaterial(params)
          .then((res) => {
            const {
              code,
              data: { res_data },
            } = res;
            if (code === 0) {
              resolve(res_data);
              return;
            }
            reject();
          })
          .catch(reject);
      });
    },

    getImagesSelectList() {
      this.imagesSelectList.forEach((item, i) => {
        const paramsNew = {
          name:this.name,
          idCard:this.idCard,
          // name: "谢逊",
          // idCard: "530121198502181698",
          fileName: item.fileName, //文件名
        };
        getImgFromCacheByFlag(paramsNew).then((result) => {
          if (result.code === 0) {
            this.$set(item, "tImg", result.data.res_data);
          }
        });
      });
    },
    // 全选
    handleCheckAllChange(check) {
      if (!this.curPersonRow) {
        this.$message({
          message: "请先选择授权人员",
          type: "warning",
        });
        return;
      }
      if (!this.currentTreeItem) {
        this.$message({
          message: "请选择相应目录树",
          type: "warning",
        });
        return;
      }
      // 选中了 全部的时候，直接让请求
      if (check) {
        this.isAllIndeterminate = false;
        this.curSelectImageList = this.imagesSelectList.map((e) => {
          return this.getDictName + "_" + e.fileName;
        });
      } else {
        // 不是选中的时候，直接让全部清空
        // this.tempImagesCheckVals = []
        this.isAllCheckbox = false;
        this.isAllIndeterminate = false;
        this.curSequlectImageList = [];
        this.imagesCheckVals = [];

        this.isAllNowadayCheckbox = false;
        this.handleCheckAllNowadayChange(false);
      }
    },
    // 全选当前目录
    handleCheckAllNowadayChange(check) {
      if (!this.curPersonRow) {
        this.$message({
          message: "请先选择授权人员",
          type: "warning",
        });
        return;
      }
      if (!this.getDictName) {
        this.$message({
          message: "请选择相应目录树",
          type: "warning",
        });
        return;
      }
      if (check) {
        this.curSelectImageList = this.imagesSelectList.map((e) => {
          return this.getDictName + "_" + e.fileName;
        });
        this.imagesCheckVals = [
          ...new Set([...this.imagesCheckVals, ...this.curSelectImageList]),
        ];
      } else {
        if (this.isAllCheckbox) {
          this.isAllCheckbox = false;
          this.isAllIndeterminate = false;
          this.isAllNowadayIndeterminate = false;
          this.isAllNowadayCheckbox = false;
          this.curSelectImageList = [];
          this.imagesCheckVals = [];
        } else {
          this.curSelectImageList.forEach((e) => {
            let imageIx = this.imagesCheckVals.indexOf(e);
            if (imageIx > -1) {
              this.imagesCheckVals.splice(imageIx, 1);
            }
          });
          this.curSelectImageList = [];
        }
      }
    },

    //单选
    handleCheckboxChange(check, val) {
      if (!this.curPersonRow) {
        this.$message({
          message: "请先选择授权人员",
          type: "warning",
        });
        return;
      }
      if (!this.currentTreeItem) {
        this.$message({
          message: "请选择相应目录树",
          type: "warning",
        });
        return;
      }
      if (check) {
        this.curSelectImageList.push(val);
        this.imagesCheckVals.push(val);
      } else {
        if (this.isAllCheckbox) {
          this.isAllCheckbox = false;
          this.isAllIndeterminate = false;
          this.isAllNowadayIndeterminate = false;
          this.isAllNowadayCheckbox = false;
          this.curSelectImageList = [];
          this.imagesCheckVals = [];
          return;
        }
        let index = this.curSelectImageList.indexOf(val);
        if (index > -1) {
          this.curSelectImageList.splice(index, 1);
        }
        let imageIx = this.imagesCheckVals.indexOf(val);
        if (imageIx > -1) {
          this.imagesCheckVals.splice(imageIx, 1);
        }
      }
    },

    // 点击小图切换大图
    hanldeSelectImage(index) {
      this.selectedImageIndex = index;
    },

    setAllChecked(check = false) {
      if (check) {
        this.isAllIndeterminate = false;
        this.isAllCheckbox = true;
      } else {
        this.isAllIndeterminate = false;
        this.isAllCheckbox = false;
      }
    },

    // 设置当前回显的数据
    setCurrentSelectImages(names) {
      if (!names) return;
      this.curSelectImageList = names.split(",");
    },

    // 设置要回显的数据
    setSelectIamge(text) {
      if (!text) return;
      let list = text.split(",");
      this.tcurrentSelectImage = list;
      this.$nextTick(() => {
        if (this.isAllCheckbox) {
        } else {
          this.imagesCheckVals = [...this.tcurrentSelectImage];
        }
      });
    },

    getEmpowerStr() {
      return {
        dataId: this.curPersonRow.dataId,
        text: this.getEmpowerText,
      };
    },

    getNotChildrens(list) {
      return list.filter((f) => !Array.isArray(f.children));
    },

    getMateItem(list) {
      const [treeItem] = list;
      if (treeItem && Array.isArray(treeItem.children)) {
        return this.getMateItem(treeItem.children);
      } else {
        return treeItem;
      }
    },

    // handlePersonListClick
    // 处理点击人员的时候 必须初始化，所有的数据，因为后面的数据是根据人员来的
    // 在这里处理个人的数据
    setSelectPersonItemData(item) {
      const { empowerLable, personName, idCard } = item || {};
      this.name = personName;
      this.idCard = idCard;
      this.curPersonRow = item;
      if (empowerLable === "全部") {
        this.setAllChecked(true);
      } else {
        this.setAllChecked(false);
        this.setSelectIamge(empowerLable);
      }
    },

    // 每当点击树形的目录就要判断是否有上次选择的
    setTreeSelectImages() {
      this.curSelectImageList = [];
      if (this.isAllCheckbox) {
        this.curSelectImageList = this.imagesSelectList.map((e) => {
          return this.getDictName + "_" + e.fileName;
        });
        return;
      }

      this.imagesSelectList.forEach((e) => {
        let val = this.getDictName + "_" + e.fileName;
        let imageIx = this.imagesCheckVals.indexOf(val);
        if (imageIx > -1) {
          this.curSelectImageList.push(val);
        }
      });
    },
  },
};
</script>

<style scoped>
>>> .el-tree-node__content {
  height: 60px;
}
.centerWarp {
  display: flex;
}
/deep/ .el-tree > .el-tree-node > .el-tree-node__content {
  font-weight: 900;
  background: #cfe5fc;
}
/deep/
  .el-tree
  > .el-tree-node
  > .el-tree-node__children
  > .el-tree-node
  > .el-tree-node__content
  > .el-tree-node__label {
  font-weight: 700;
}
/deep/.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background: #6baef1;
}

>>> .el-tree-node__content {
  /* background-color: #CFE5FC; */
  margin-top: 2px;
}

.highlight {
  background-color: #c6e2ff;
  padding: 5px;
  height: 40px;
}

.nameStyle {
  width: 400px;
  text-align: center;
  font-size: 18px;
  color: #409eff;
  overflow-y: scroll;
}
.nameStyle p {
  padding: 5px;
  height: 40px;
}

.selectimgs-warp {
  width: 240px;
  text-align: center;
  margin-left: 5px;
  overflow-y: scroll;
}
/* 工作单位及职务 */
.selectimgs-warp {
  padding: 5px;
  height: 40px;
}

.dc-tree-c {
  margin-left: 10px;
  margin-top: 5px;
  margin-bottom: 5px;
}

.left {
  float: left;
  margin-left: 5px;
  background: #f7f2ec;
  width: 18.417vw;
  overflow-y: scroll;
}
.right {
  float: left;
  margin-left: 15px;
  background: #f7f2ec;
}
.thumbnail {
  width: 230px;
  overflow-y: scroll;
  float: left;
  margin-bottom: 5px;
  background: #fff;
}
.image-container {
  display: flex;
  padding-right: 0.521vw;
  margin-top: 5px;
  justify-content: space-around;
}
/* 将el-checkbox中的label隐藏了 */
.image-container /deep/.el-checkbox__label {
  display: none;
}
.bigPicture {
  float: left;
  width: 600px;
  margin-bottom: 5px;
  margin-right: 10px;
  background: #fff;
  margin-left: 10px;
}

.cd-checkiam {
  width: 140px;
  height: 200px;
}

.cd-checkiam.check-active {
  border: 2px solid red;
}
.myTable {
  border:none;
  margin-bottom: 10px;
  border-spacing: 0;
}
.myTable td {
  word-wrap: break-word;
  font-size: 14px;
  text-align: center;
  padding: 5px 10px;
  border:none;
}
</style>